﻿using Microsoft.VisualStudio.Modeling;
using System;
using System.Text;

namespace Project.Co_DataTransformationPrototype
{
    class RemovalMapping : MappingBase
    {

        public RemovalMapping(EventContext eventContext)
        {
            this.eventContext = eventContext;
            //generateSQLCodeMapping();
        }

        internal override void generateSQLCodeMapping(StringBuilder existingScript = null)
        {
            strSQLMapping = new StringBuilder();

            if (existingScript != null)
                strSQLMapping.Append(existingScript);

            if (typeof(Entity).Equals(eventContext.elementEventArgs.ModelElement.GetType()))
                removeTableSQLCode();
            else if (typeof(EntityAttribute).Equals(eventContext.elementEventArgs.ModelElement.GetType()))
                removeColumnSQLCode();
        }

        private void removeTableSQLCode()
        {
            ElementDeletedEventArgs eArgs = (ElementDeletedEventArgs) eventContext.elementEventArgs;
            Entity entity = eArgs.ModelElement as Entity;

            strSQLMapping.AppendFormat("IF OBJECT_ID('[{0}].{1}', 'U') IS NOT NULL" + Environment.NewLine, Data.DatabaseSettings.SHEMA_NAME, eventContext.entityName);
            strSQLMapping.AppendFormat("    DROP TABLE [{0}].{1}" + Environment.NewLine, Data.DatabaseSettings.SHEMA_NAME, eventContext.entityName);
            strSQLMapping.AppendLine("GO" + Environment.NewLine);
        }

        private void removeColumnSQLCode()
        {
            EntityAttribute attribute = eventContext.elementEventArgs.ModelElement as EntityAttribute;

            strSQLMapping.AppendFormat("ALTER TABLE [{0}].{1}" + Environment.NewLine, Data.DatabaseSettings.SHEMA_NAME, eventContext.entityName);
            strSQLMapping.AppendFormat("    DROP COLUMN {0}" + Environment.NewLine, attribute.CurrentName);
            strSQLMapping.AppendLine("GO" + Environment.NewLine);
        }

    }
}
